<?php

/**
 * 收案表
 */

namespace app\common\model;

use app\common\lib\Redis;
use app\common\lib\ZhyxMongo;
use app\common\model\PatientInfo as PatientInfoModel;
use app\common\model\CollectClass as CollectClassModel;
use app\common\model\search\CollectCaseSearch;
use app\common\utils\Str;
use MongoDB\BSON\ObjectId;

class CollectCase extends BaseModel
{
    use CollectCaseSearch;

    protected $name = "collect_case";

    /**
     * 获取数据列表
     * @param int $tag 1列表 2数据
     * @param array $outField 过滤字段
     */
    public function getList(int $tag = 1, array $outField = [])
    {

        $where = [];
        $doctorId = request()->param("doctor_id", "", "string");

        $user = request()->user();
        $customDeptId = (int)request()->header("custom-dept-id");
        if (!empty($customDeptId)) {
            $departId = $customDeptId;
            $user['department_id'] = $departId;
        }

        $whereOr=[];
        if ($doctorId) {
            $where[] = ["doctors.attendingDoctorNo", "=", $doctorId];
        } else {
            $whereOr = [["creator_id", "=", $user["id"]], ["dept_id", "=", $user["department_id"]]];
        }

        if ($tag == 1) {
            $page = request()->param("page", 1, "int");
            $patientIds = $this->mongoSearch([], [], ['liveStatus','disease_path_id','doctor_id'])->where($where)->whereOr($whereOr)->column('patientId');

            $match['patientId'] = ['$in' => $patientIds];
            $match['deleted_at'] = 0;

            if (trim($user["dept_code"])) {
                $match['dept_id'] = (int)$user["dept_code"];
            }


            //随访路径筛选
            $disease_path_id = request()->param("disease_path_id", '', "string");
            $disease_path = [];
            if (!empty($disease_path_id)) {
                $disease_path['disease_path.deleted_at'] = 0;
                $disease_path['disease_path.disease_path_id'] = $disease_path_id;
            }

            $countPip = [['$match' => $match], ['$lookup' => ['from' => 'patient_info', 'localField' => 'patientId', 'foreignField' => 'patientId', 'as' => 'info']], ['$unwind' => ['path' => '$info', 'preserveNullAndEmptyArrays' => true]], ['$lookup' => ['from' => 'bind_disease_path', 'let' => ['patientId' => '$patientId'], 'pipeline' => [['$match' => ['$expr' => ['$and' => [['$eq' => ['$patient_id', '$$patientId']], ['$eq' => ['$deleted_at', 0]]]]]]], 'as' => 'disease_path']], ['$project' => ['_id' => false, 'id' => '$_id', 'birthdate' => '$info.birthdate', 'created_at' => '$created_at', 'creator_id' => '$creator_id', 'diagnosis' => '$diagnosis', 'name' => '$name', 'sex' => '$sex', 'pid' => '$pid', 'patientId' => '$patientId', 'presentTelphone' => '$info.presentTelphone', 'liveStatus' => '$info.liveStatus', 'updated_at' => '$updated_at', 'is_setting_monitor' => '$info.is_setting_monitor', 'monitor' => '$info.monitor', 'attention' => '$attention', 'disease_path' => '$disease_path']], ['$match' => $disease_path ?: (object)[]], ['$match' => ['$or' => [['attention' => request()->user()->id], ['attention' => null], ['attention' => []]]]], ['$sort' => ['attention' => -1]], ['$count' => 'total_count']];
            $countResult = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($countPip);

            $totalCount = 0;
            foreach ($countResult as $k => $v) {
                $totalCount = $v["total_count"];
            }

            //查询数据
            $pip = [['$match' => $match], ['$lookup' => ['from' => 'patient_info', 'localField' => 'patientId', 'foreignField' => 'patientId', 'as' => 'info']], ['$unwind' => ['path' => '$info', 'preserveNullAndEmptyArrays' => true]], ['$lookup' => ['from' => 'bind_disease_path', 'let' => ['patientId' => '$patientId'], 'pipeline' => [['$match' => ['$expr' => ['$and' => [['$eq' => ['$patient_id', '$$patientId']], ['$eq' => ['$deleted_at', 0]]]]]]], 'as' => 'disease_path']], ['$project' => ['_id' => false, 'id' => '$_id', 'birthdate' => '$info.birthdate', 'created_at' => '$created_at', 'creator_id' => '$creator_id', 'diagnosis' => '$diagnosis', 'name' => '$name', 'sex' => '$sex', 'pid' => '$pid', 'patientId' => '$patientId', 'presentTelphone' => '$info.presentTelphone', 'liveStatus' => '$info.liveStatus', 'updated_at' => '$updated_at', 'is_setting_monitor' => '$info.is_setting_monitor', 'monitor' => '$info.monitor', 'attention' => '$attention', 'disease_path' => '$disease_path']], ['$match' => $disease_path ?: (object)[]], ['$match' => ['$or' => [['attention' => request()->user()->id], ['attention' => null], ['attention' => []]]]], ['$skip' => (($page - 1) * $this->pageLimit)], ['$sort' => ['attention' => -1, 'created_at' => -1]], ['$limit' => $this->pageLimit]];

            $data = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($pip);

            $ret = [];
            $pids = [];
            foreach ($data as $key => $val) {
                $ret[] = (array)$val;
            }
            foreach ($ret as $key => $val) {
                $pids[] = $val['pid'];
                $ret[$key]['id'] = (string)$val['id'];
                $ret[$key]['presentTelphone'] = $val['presentTelphone'] ?? '';
                $ret[$key]['created_at'] = date("Y-m-d H:i:s", $val['created_at']);
                $ret[$key]['updated_at'] = date("Y-m-d H:i:s", $val['updated_at']);
                if (empty($val['is_setting_monitor'])) {
                    $ret[$key]['is_setting_monitor'] = false;
                }
                if (empty($val['monitor'])) {
                    $ret[$key]['monitor'] = [];
                }
            }

            $key = uniqid('collect');
            if (!empty($pids)) {
                Redis::getInstance()->redis->setex("collect_pids:" . $key, 1800, json_encode($pids));
            }

            return [
                "count" => $totalCount ?: 0,
                "current" => $page,
                "limit" => $this->pageLimit,
                "data" => $ret,
                "skip" => (($page - 1) * $this->pageLimit),
                "key" => $key
            ];
        } else {
            return $this->mongoSearch([], [], $outField)
                ->where($where)
                ->field('pid,name,patientId,sex')
                ->order('attention', 'desc')
                ->select()
                ->toArray();
        }
    }

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $data): string
    {
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 取消收案患者
     * @param array $param
     */
    public function delCase(array $param)
    {
        return self::destroy($param['id']);
    }

    /**
     * 获取key => value结构数据
     * @param array $where 条件
     * @param string $val 输出字段
     * @return array
     */
    public function getKeyVal(array $where = [], string $val = 'pid'): array
    {
        return $this->where($where)->column($val);
    }

    /**
     * 获取所有收案患者
     */
    public function getCollectPatient()
    {
        //从收案中查询患者
        $collect = $this->field('pid')->select()->toArray();

        $data = [];
        foreach ($collect as $key => $val) {
            unset($val['id']);
            $data[] = implode(',', $val);
        }
        return implode(',', $data);
    }

    /**
     * 获取医生端收案患者列表
     */
    public function getYsdCase($class_id)
    {
        $users = $this->getUserJurisdiction('');
        $where = [];
        if (!empty($users)) {
            $pids = (new PatientInfoModel())->where($users)->column('id');
            $where[] = ['pid', 'in', $pids];
        }

        $patient = (new CollectClassModel())->where('id', $class_id)->field('patientList')->find();

        //如果分组下绑定了患者
        $data = [];
        if (isset($patient['patientList']) && !empty($patient['patientList'])) {
            $ids = [];
            foreach ($patient['patientList'] as $key => $val) {
                $ids[] = $val['patient_id'];
            }
            $where[] = ['patientId', 'in', $ids];
            $data['count'] = $this->mongoSearch()->where($where)->count();
            $data['list'] = $this->mongoSearch()
                ->where($where)
                ->field('pid,patientId,name,diagnosis,sex')
                ->select();
        }
        return $data;
    }

    /**
     * 医生端模糊搜索收案患者
     */
    public function searchCasePatient($creator_id, $name)
    {
        $where[] = ['patientList.name', 'like', $name];
        $where[] = ['type', '=', 1];
        $where[] = ['creator_id', '=', $creator_id];
        $classList = (new CollectClassModel)->where($where)->field('className,patientList')->select()->toArray();

        $datas = [];
        foreach ($classList as $key => $val) {
            $data['className'] = $val['className'];
            $d1s = [];
            foreach ($val['patientList'] as $k1 => $v1) {
                $patient = $this->whereLike('name', $name)->where('patientId', $v1['patient_id'])->find();
                if ($patient <> null) {
                    $d1s[] = $patient;
                }
            }
            $data['data'] = $d1s;
            $datas[] = $data;
        }
        return $datas;
    }
}
